/**
 * 试用中列表页面(带测试功能)
 */
import React from 'react';
import { Table, Form, Input, DatePicker, message, Tooltip, Menu, Dropdown } from 'antd';
import { withRouter, router } from 'umi';
import { connect } from 'umi';
import { toNumber } from 'lodash';
import moment from 'moment';
// import authHelper from '@/utils/auth/helper';
import { DividerContainer } from '@/molecules';
import { Pagination, CollapseSearch } from '@/components';
import { Company, Organization, Grade } from '@/containers';
import { useRequest, defaultFormatResult } from '@/hooks';
import { Icon } from '@/pages/Recruitment/components';
import { SelectPost } from '@/pages/Recruitment/containers/select';
import { dictionaryList } from '@/services/dictionary';
import { primaryColor } from '@/defaultSettings';
import { sameTabProps } from '@/utils/tab';

import { queryInformalList, getFeedbackNum, getProcessInfo } from '../services';
import { test } from '../services/test'; // 模拟转正考评流程
import {
    TRIAL_STATUS_LIST,
    LIST_TYPE,
    TRIAL_ACTION_LIST,
    INFORMAL_STATUS_LIST,
    RECORD_STATUS_LIST
} from '../constants';
import { getStatusList, renderActionIcon, getInterviewTip } from '../utils';
import styles from './index.less';

// const { checkCode } = authHelper;

const Trial = ({ form, location, type, user }) => {
    const { query = {} } = location;

    const [expand, setExpand] = React.useState(query?.expand === '1' || false);

    const { data, loading, run, refresh } = useRequest(queryInformalList, {
        manual: true,
        ...defaultFormatResult
    });

    const dataSource = data?.rows || [];
    const total = data?.total || 0;

    // 获取表单字典
    const { data: workNatureList } = useRequest(
        () =>
            dictionaryList({
                codes: ['jobNature']
            }),
        {
            initialData: [],
            formatResult: res => {
                if (res) {
                    const { code, data: resData, msg } = res;
                    if (code === 10000) {
                        return resData.map(({ dictValue, dictName }) => ({
                            text: dictName,
                            value: dictValue
                        }));
                    }
                    message.error(msg);
                }
                return [];
            }
        }
    );

    const { loading: feedbackLoading, run: fetchFeedbackNum } = useRequest(getFeedbackNum, {
        manual: true,
        onSuccess: (res, params) => {
            if (res) {
                const { code, data: resData, msg } = res;
                if (code === 10000) {
                    let url = '/office/personnelManagement/onboardAndLeave/informal/feedback/record';
                    if (resData <= 0) {
                        url = '/office/personnelManagement/onboardAndLeave/informal/feedback/create';
                    }
                    history.push({
                        pathname: url,
                        query: { id: params?.[0], employeeCode: params?.[1] },
                        ...sameTabProps
                    });
                } else {
                    message.error(msg);
                }
            } else {
                message.error('操作失败');
            }
        }
    });

    const { loading: processLoading, run: fetchProcess } = useRequest(getProcessInfo, {
        manual: true,
        onSuccess: (res, params) => {
            if (res) {
                const { code, data: resData, msg } = res;
                if (code === 10000) {
                    history.push({
                        pathname: '/personal/portal/waitApproval/approvalDetail',
                        query: {
                            taskId: resData?.id,
                            processInstanceName: `转正申请${params?.[1] ? ` - ${params?.[1]}` : ''}`
                        }
                    });
                } else {
                    message.error(msg);
                }
            } else {
                message.error('操作失败');
            }
        }
    });

    // url参数变化时触发接口请求数据
    // 注：部分参数类型为数组时，统一保存为以","分隔的字符串，因此请求时需转换为数组格式
    // 注：部分参数类型为Number时，需调用toNumber转换，确保数据类型准确
    React.useEffect(() => {
        const {
            activeKey,
            expand: _expand,
            orderByField = '',
            sex,
            workNature,
            status,
            rankValueList,
            ...rest
        } = query;
        const sexList = sex ? sex.split(',') : '';
        const workNatures = workNature ? workNature.split(',') : '';
        const statusList = status ? status.split(',') : '';
        let finalStatus = statusList || [];
        if (type === LIST_TYPE.TRIAL) {
            finalStatus = getStatusList(statusList ? statusList.map(item => toNumber(item)) : []);
        } else if (type === LIST_TYPE.INFORMAL) {
            if (statusList.includes('regularApply')) {
                finalStatus = [...statusList, 'regularApplyAhead'];
            }
        }

        run({
            ...rest,
            sexList: sexList || [],
            workNatureList: workNatures || [],
            statusList: finalStatus,
            rankValueList: rankValueList ? rankValueList.split(',') : [],
            orderByField: orderByField.replace('end', ''),
            type
        });
    }, [query]);

    const handleAction = React.useCallback((record, status) => {
        history.push({
            pathname: '/office/personnelManagement/onboardAndLeave/informal/process',
            query: {
                employeeCode: record?.employeeCode || '',
                status: status || record?.status || ''
            }
        });
    }, []);

    const getOrderState = field => {
        if (!query?.orderByField) {
            return undefined;
        }
        const arr = query.orderByField.split('|');
        if (arr[0] === field) {
            return arr[1];
        }
        return undefined;
    };

    const { loading: testLoading, run: runTest } = useRequest(test, {
        manual: true,
        onSuccess: res => {
            if (res) {
                const { code, msg } = res;
                if (code === 10000) {
                    refresh();
                } else {
                    message.error(msg);
                }
            } else {
                message.error('操作失败');
            }
        }
    });

    const handleMenuClick = (key, record) => {
        runTest(key, record?.employeeCode);
    };

    const renderMenu = record => {
        const { status } = record;
        let round = 1;
        if (status.endsWith('Complete')) {
            round = 2;
        } else if (record.status.startsWith('interviewDetail')) {
            round = 3;
        }
        return (
            <Menu onClick={({ key }) => handleMenuClick(key, record)}>
                {round === 1 && <Menu.Item key="1">完成当次考评</Menu.Item>}
                <Menu.Item key="2">开启新一轮考评</Menu.Item>
                {round !== 3 && <Menu.Item key="3">完成所有考评</Menu.Item>}
                <Menu.Item key="4">初始化</Menu.Item>
            </Menu>
        );
    };

    const renderDropDown = record => {
        if (record.status.startsWith('interview') && !record.status.startsWith('interviewDetail')) {
            return null;
        }
        return (
            <Dropdown overlay={renderMenu(record)} getPopupContainer={trigger => trigger.parentElement}>
                <Icon title="测试按钮" type="listfunction_more_icon_default" onClick={() => {}} />
            </Dropdown>
        );
    };

    const columns = [
        {
            title: '姓名',
            dataIndex: 'employeeName',
            render: (text, record) =>
                record.leaderPositionFlag ? (
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                        {text}
                        <Icon
                            title="主管"
                            type="LeaderMark"
                            style={{ color: primaryColor, fontSize: 18, marginLeft: 4 }}
                        />
                    </div>
                ) : (
                    text
                )
        },
        {
            title: '性别',
            dataIndex: 'sex',
            filteredValue: query?.sex && query?.sex.split(','),
            filters: [
                { text: '男', value: '1' },
                { text: '女', value: '2' }
            ],
            render: (text, record) => ['', '男', '女'][record.sex] || ''
        },
        {
            title: '组织机构',
            dataIndex: 'organizationName',
            render: (text, record) => {
                if (!text) return '';
                return <Tooltip title={record?.fullOrganizationName || ''}>{text}</Tooltip>;
            }
        },
        {
            title: '岗位',
            dataIndex: 'dutyName',
            render: (text, record) => `${text}${text && record.rankValue ? '/' : ''}${record.rankValue}`
        },
        {
            title: '行政机构',
            dataIndex: 'companyName'
        },
        {
            title: '入职日期',
            dataIndex: 'entryDate',
            sortOrder: getOrderState('entryDate'),
            sorter: () => {}
        },
        {
            title: '试用期',
            dataIndex: 'probationPeriodNumber',
            render: (text, record) => {
                if (!text) return '';
                if (record?.probationPeriodType === 1) {
                    return `${text}个月`;
                }
                return `${text}天`;
            }
        },
        {
            title: '工作性质',
            dataIndex: 'workNature',
            filteredValue: query?.workNature && query?.workNature.split(','),
            filters: workNatureList || [],
            render: text => workNatureList.find(item => item.value === text)?.text || ''
        },
        {
            title: '状态',
            dataIndex: 'status',
            filteredValue: query?.status && query?.status.split(','),
            filters: TRIAL_STATUS_LIST,
            render: (text, record) => {
                if (!text) return '';
                const obj = TRIAL_ACTION_LIST.find(item => item.value === text);
                const tip = getInterviewTip(record, user);
                return tip || obj?.status || obj?.title || '';
            }
        },
        {
            title: '操作',
            dataIndex: 'action',
            width: 140,
            fixed: 'right',
            className: styles.tableAction,
            onCell: () => ({
                onClick: e => {
                    e.stopPropagation();
                }
            }),
            render: (text, record) => (
                <DividerContainer>
                    {renderActionIcon(record, user, handleAction)}
                    {false && (
                        <Icon
                            title="试用反馈"
                            type="shiyongfankui"
                            onClick={() => {
                                fetchFeedbackNum(record?.id, record?.employeeCode);
                            }}
                        />
                    )}
                    {/* {checkCode('office:recruitment:setting:channel:template:update') && (
                        <Icon
                            title="试用反馈"
                            type="huifu"
                            onClick={() => {
                                fetchFeedbackNum(record?.id, record?.employeeCode);
                            }}
                        />
                    )} */}
                    {/* <Icon title="沟通新员工" type="goutong" onClick={() => {}} /> */}
                    {renderDropDown(record)}
                </DividerContainer>
            )
        }
    ];

    if (type === LIST_TYPE.INFORMAL) {
        columns[7] = {
            title: '预计转正',
            dataIndex: 'expectRegularDate',
            sortOrder: getOrderState('expectRegularDate'),
            sorter: () => {}
        };
        columns[8] = {
            title: '状态',
            dataIndex: 'status',
            filteredValue: query?.status && query?.status.split(','),
            filters: INFORMAL_STATUS_LIST,
            render: text => {
                if (!text) return '';
                const obj = INFORMAL_STATUS_LIST.find(item => item.value === text || item?.value2 === text);
                return <span style={{ color: obj?.color || '' }}>{obj?.text || ''}</span>;
            }
        };
        columns[9] = {
            title: '操作',
            dataIndex: 'action',
            width: 120,
            fixed: 'right',
            className: styles.tableAction,
            onCell: () => ({
                onClick: e => {
                    e.stopPropagation();
                }
            }),
            render: (text, record) => {
                if (record?.processInstanceId) {
                    return (
                        <DividerContainer>
                            <Icon
                                title="转正申请审批"
                                type="shenpizhuanzhengshenqing"
                                onClick={() => {
                                    fetchProcess(record?.processInstanceId, record?.employeeName || '');
                                }}
                            />
                        </DividerContainer>
                    );
                }
                return null;
            }
        };
    } else if (type === LIST_TYPE.RECORD) {
        columns[7] = {
            title: '转正日期',
            dataIndex: 'regularDate',
            sortOrder: getOrderState('regularDate'),
            sorter: () => {}
        };
        columns[8] = {
            title: '状态',
            dataIndex: 'status',
            filteredValue: query?.status && query?.status.split(','),
            filters: RECORD_STATUS_LIST,
            render: text => {
                if (!text) return '';
                const obj = RECORD_STATUS_LIST.find(item => item.value === text);
                return <span style={{ color: obj?.color || '' }}>{obj?.text || ''}</span>;
            }
        };
        columns.pop();
        // columns[9] = {
        //     title: '操作',
        //     dataIndex: 'action',
        //     width: 120,
        //     fixed: 'right',
        //     className: styles.tableAction,
        //     onCell: () => ({
        //         onClick: e => {
        //             e.stopPropagation();
        //         }
        //     })
        // };
    }

    const handlePaginationChange = pagination => {
        const { current, pageSize } = pagination;
        history.push({ query: { ...query, pageNo: current, pageSize } });
    };

    const handleTableChange = (_, filters = {}, sorter) => {
        const { sex = [], workNature = [], status = [] } = filters;
        const { field, order } = sorter;
        history.push({
            query: {
                ...query,
                sex: sex ? sex.join(',') : undefined,
                workNature: workNature ? workNature.join(',') : undefined,
                status: status ? status.join(',') : undefined,
                orderByField: order ? `${field}|${order}` : undefined,
                pageNo: 1
            }
        });
    };

    const handleSubmit = () => {
        form.validateFields((err, values) => {
            if (!err) {
                const { rankValueList, rangeTime, ...rest } = values;
                history.push({
                    query: {
                        ...query,
                        ...rest,
                        expand: expand ? '1' : '0',
                        rankValueList: rankValueList ? rankValueList.join(',') : undefined,
                        entryDateStart: rangeTime?.length > 0 ? rangeTime[0].format('YYYY-MM-DD') : undefined,
                        entryDateEnd: rangeTime?.length > 1 ? rangeTime[1].format('YYYY-MM-DD') : undefined,
                        pageNo: 1
                    }
                });
            }
        });
    };

    return (
        <>
            <CollapseSearch expanded={query?.expand === '1' || false} onSubmit={handleSubmit} onExpand={setExpand}>
                <Form.Item label="">
                    {form.getFieldDecorator('keyword', {
                        initialValue: query?.keyword || undefined
                    })(
                        <Input style={{ width: 252 }} placeholder="搜索姓名、员工号、邮箱" allowClear maxLength={200} />
                    )}
                </Form.Item>
                <Form.Item label="机构" style={{ marginRight: 8 }}>
                    {form.getFieldDecorator('companyCode', {
                        initialValue: query?.companyCode || undefined
                    })(
                        <Company
                            placeholder="请选择行政机构"
                            getPopupContainer={triggerNode => triggerNode.parentElement}
                            style={{ width: 304 }}
                        />
                    )}
                </Form.Item>
                <Form.Item>
                    {form.getFieldDecorator('organizationCode', {
                        initialValue: query?.organizationCode || undefined
                    })(
                        <Organization
                            placeholder="请选择组织机构"
                            getPopupContainer={triggerNode => triggerNode.parentElement}
                            style={{ width: 304 }}
                        />
                    )}
                </Form.Item>
                <Form.Item label="岗位" collapsed>
                    {form.getFieldDecorator('dutyCode', {
                        initialValue: query?.dutyCode || undefined
                    })(<SelectPost placeholder="请选择岗位" style={{ width: 210 }} />)}
                </Form.Item>
                <Form.Item label="职级">
                    {form.getFieldDecorator('rankValueList', {
                        initialValue: query?.rankValueList ? query?.rankValueList.split(',') : undefined
                    })(<Grade style={{ width: 210 }} />)}
                </Form.Item>
                <Form.Item label="入职日期">
                    {form.getFieldDecorator('rangeTime', {
                        initialValue:
                            query?.entryDateStart && query?.entryDateEnd
                                ? [moment(query.entryDateStart), moment(query.entryDateEnd)]
                                : undefined
                    })(<DatePicker.RangePicker style={{ width: 230 }} />)}
                </Form.Item>
            </CollapseSearch>
            <Table
                className={styles.fixedAction}
                rowKey="id"
                rowClassName={styles.tableRow}
                columns={columns}
                dataSource={dataSource}
                pagination={false}
                scroll={{ x: 'max-content' }}
                onChange={handleTableChange}
                loading={loading || feedbackLoading || processLoading || testLoading}
                onRow={record => ({
                    onClick: () => {
                        history.push({
                            pathname: '/office/personnelManagement/onboardAndLeave/informal/detail',
                            query: {
                                id: record?.id,
                                employeeCode: record?.employeeCode
                            }
                        });
                    }
                })}
            />
            <Pagination
                current={query.pageNo}
                pageSize={query.pageSize}
                loading={loading}
                total={total}
                onChange={handlePaginationChange}
            />
        </>
    );
};

export default withRouter(connect(({ user }) => ({ user: user.currentUser }))(Form.create()(Trial)));
